package com.hzlj.position.locate.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.core.date.DateUtils;
import com.fz.common.base.dto.PageParamDTO;
import com.fz.common.base.dto.QueryPageResultDTO;
import com.fz.common.base.exception.PubError;
import com.fz.common.base.exception.PubException;
import com.fz.common.dict.annotation.DictConvert;
import com.google.common.collect.Maps;
import com.hzlj.common.message.common.dto.message.MessageNoticeResultDTO;
import com.hzlj.common.message.common.dto.message.MessageNoticeUserDTO;
import com.hzlj.common.message.common.util.MessageRestUtil;
import com.hzlj.position.config.service.NoticeConfigService;
import com.hzlj.position.locate.common.common.AbnWarningTrackDTO;
import com.hzlj.position.locate.common.dto.abnProhibitAreasPosition.AbnProhibitAreasPositionAddDTO;
import com.hzlj.position.locate.common.dto.abnProhibitAreasPosition.AbnProhibitAreasPositionQueryParamDTO;
import com.hzlj.position.locate.common.dto.abnProhibitAreasPosition.AbnProhibitAreasPositionQueryResultDTO;
import com.hzlj.position.locate.common.model.AbnProhibitAreasPosition;
import com.hzlj.position.locate.converter.AbnProhibitAreasPositionConverter;
import com.hzlj.position.locate.dao.AbnProhibitAreasPositionDao;
import com.hzlj.position.locate.service.AbnProhibitAreasPositionService;
import com.hzlj.sqjz.jz.cache.JzJbxxCache;
import com.hzlj.sqjz.jz.common.dto.common.JzJbxxCacheDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.hzlj.position.config.config.IdConfig.POSITION_ID_GEN;

/**
 * 禁止区域-定位记录(AbnProhibitAreasPosition)表服务接口
 *
 * @author lifh
 * @date 2023-03-28 10:20:37
 */
@Slf4j
@Service
public class AbnProhibitAreasPositionServiceImpl implements AbnProhibitAreasPositionService {
    @Resource
    private AbnProhibitAreasPositionDao abnProhibitAreasPositionDao;
    @Resource
    private JzJbxxCache jzJbxxCache;
    @Resource
    private NoticeConfigService noticeConfigService;


    /**
     * 通过id查询单条数据
     *
     * @param id id
     * @return 实例对象
     */
    @Override
    public AbnProhibitAreasPositionQueryResultDTO getAbnProhibitAreasPositionById(String id) {
        AbnProhibitAreasPosition abnProhibitAreasPosition = this.abnProhibitAreasPositionDao.getById(id);
        if (Objects.isNull(abnProhibitAreasPosition)) {
            throw new PubException(PubError.NO_OBJECT_FOUND);
        }
        return AbnProhibitAreasPositionConverter.from(abnProhibitAreasPosition);
    }

    @Override
    public AbnWarningTrackDTO getWarningTrack(String id) {
        return abnProhibitAreasPositionDao.getAWarningTrack(id);
    }

    /**
     * 新增数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAbnProhibitAreasPosition(List<AbnProhibitAreasPositionAddDTO> dtos) {
        if (ObjectUtil.isEmpty(dtos)) {
            return;
        }
        List<AbnProhibitAreasPosition> adds = dtos.stream()
                .map(AbnProhibitAreasPositionConverter::from)
                .peek(e -> e.setId(POSITION_ID_GEN.nextIdStr()))
                .collect(Collectors.toList());
        this.abnProhibitAreasPositionDao.saveBatch(adds);

        //发送通知
        this.notice(adds);
    }

    /**
     * 发送通知
     */
    private void notice(List<AbnProhibitAreasPosition> positions) {
        for (AbnProhibitAreasPosition position : positions) {
            try {
                //发送给矫正人员
                MessageNoticeResultDTO noticeJzry = this.noticeJzry(position);
                //发送给工作人员
                MessageNoticeResultDTO noticeGzry = this.noticeGzry(position);
                //跟踪日志
                AbnWarningTrackDTO track = new AbnWarningTrackDTO();
                track.setToJzry(AbnWarningTrackDTO.Notice.parse(noticeJzry));
                track.setToGzry(AbnWarningTrackDTO.Notice.parse(noticeGzry));
                this.abnProhibitAreasPositionDao.updateWarningTrack(position.getId(), track);
            } catch (Exception e) {
                log.warn("发送定位告警消息失败,position={},err={}", position, e.getMessage());
            }
        }
    }


    /**
     * 发送通知
     */
    private MessageNoticeResultDTO noticeJzry(AbnProhibitAreasPosition position) {
        Map<String, Object> noticeParams = Maps.newHashMap();
        noticeParams.put("positionTime", DateUtils.formatDate(position.getPositionTime()));
        return MessageRestUtil.noticeQueryUsers(
                "abn-prohibit-areas",
                position.getId(),
                noticeParams,
                false,
                position.getJzId()
        );
    }

    private MessageNoticeResultDTO noticeGzry(AbnProhibitAreasPosition position) {
        JzJbxxCacheDTO jzJbxx = jzJbxxCache.getJzJbxxByJzId(position.getJzId());
        Map<String, Object> params = Maps.newHashMap();
        params.put("jzryXm", jzJbxx.getXm());
        params.put("jzrySjh", jzJbxx.getSjh());
        params.put("abnTypeText", "进入禁止区域");
        params.put("positionTime", DateUtil.formatDateTime(position.getPositionTime()));
        List<MessageNoticeResultDTO> noticeResult = MessageRestUtil.noticeQueryUsers(
                "abn-prohibit-areas-gzry",
                position.getId(),
                params,
                MessageNoticeUserDTO.of(true, jzJbxx.getJgCode(), noticeConfigService.defaultMessageNoticeAuths(jzJbxx.getJgCode()))
        );
        return MessageRestUtil.getPrioritySuccess(noticeResult);
    }

    /**
     * 查询列表：分页
     */
    @Override
    @DictConvert
    public QueryPageResultDTO<AbnProhibitAreasPositionQueryResultDTO> pageAbnProhibitAreasPosition(AbnProhibitAreasPositionQueryParamDTO dto, PageParamDTO page) {
        return this.abnProhibitAreasPositionDao.pageAbnProhibitAreasPosition(dto, page);
    }
}
